package com.example.myshools.Activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.myshools.R;
import com.example.myshools.entity.Activities;
import com.example.myshools.entity.ActivityApplyData;
import com.example.myshools.entity.Constant;
import com.example.myshools.entity.EventMessage;
import com.example.myshools.entity.Img;
import com.example.myshools.entity.Orgnat;
import com.example.myshools.Mine.organization.information.OrganizationMainActivity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

public class ActivitiesItemAdapter extends BaseAdapter {

    private List<Activities> dataSource = new ArrayList<>();
    private int resId;//布局
    private Context context;//上下文
    private int randomPosition=-1;
    private int is=1;//用来设置是否需要再次取消占位
    private SharedPreferences sharedPreferences;
    private int role;
    private SharedPreferences roleShare;
    private int userId;
    private int isIdentity=1;//用户是否已经验证
    private CountDownTimer timer;
    private AlertDialog dialog;




    public ActivitiesItemAdapter(Context context, List<Activities> dataSource, int resId) {

        this.dataSource = dataSource;
        this.context = context;
        this.resId = resId;
        EventBus.getDefault().register(this);

        roleShare=context.getSharedPreferences("role",MODE_PRIVATE);
        role=roleShare.getInt("role",-1);
        if(role==0){
            //获取组织id
        }if(role==1){//获取学生Id
            sharedPreferences=context.getSharedPreferences("user", MODE_PRIVATE);
            userId=sharedPreferences.getInt("userId",-1);
            isIdentity=sharedPreferences.getInt("isIdentity",-1);
        }
    }

    @Override
    public int getCount() {
        return dataSource.size();
    }
    @Override
    public Object getItem(int i) {
        return dataSource.get(i);
    }
    @Override
    public long getItemId(int i) {
        return dataSource.get(i).getId();
    }
    @Override
    public View getView(final int position, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        RequestOptions requestOptions = new RequestOptions().placeholder(R.drawable.loading).fallback(R.drawable.loading).error(R.drawable.headfail).diskCacheStrategy(DiskCacheStrategy.ALL).circleCrop();

        if (view == null) {
            view = LayoutInflater.from(context).inflate(resId, null);
            holder = new ViewHolder();
            holder.headImg = view.findViewById(R.id.img_header);
            holder.name = view.findViewById(R.id.name);
            holder.title = view.findViewById(R.id.ac_title);
            holder.lev = view.findViewById(R.id.lev);
            holder.upDay = view.findViewById(R.id.up_day);
            holder.upTime = view.findViewById(R.id.up_time);
            holder.gridView = view.findViewById(R.id.grid_view);
            holder.content = view.findViewById(R.id.content_text);
            holder.list_biaoqian = view.findViewById(R.id.list_biao_qian);
            holder.num_views = view.findViewById(R.id.num_liulan);
            holder.content_main = view.findViewById(R.id.content_main);
            holder.button = view.findViewById(R.id.a_apply);
            holder.ac_status = view.findViewById(R.id.ac_status);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }


        final Activities activities = dataSource.get(position);
        String time = activities.getUpTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");//设置日期格式
        String currentTime = df.format(new Date());
        String a_day = time.substring(0, 8);
        if (activities.getStatus() == 0) {
            holder.ac_status.setText("活动结束");
        } else if (activities.getStatus() == 1) {
            holder.ac_status.setText("正在进行中");
        }
        int d = Integer.parseInt(a_day);

        String c_day = currentTime.substring(0, 8);
        int c = Integer.parseInt(c_day);
        if (a_day.equals(c_day)) {//表示是当天发的活动
            holder.upDay.setText("今天");
        } else if (c - 1 == d) {
            holder.upDay.setText("昨天");
        } else if (c - 2 == d) {
            holder.upDay.setText("前天");
        } else {
            holder.upDay.setText(a_day.substring(0, 4) + "." + a_day.substring(4, 6) + "." + a_day.substring(6, 8));
        }

        holder.upTime.setText(time.substring(8, 10) + ":" + time.substring(10, 12));
        //发布者信息
        final Orgnat orgnat = dataSource.get(position).getOrgnat();
        RequestOptions requestOptions1 = new RequestOptions().placeholder(R.drawable.toux).fallback(R.drawable.toux).error(R.drawable.toux).diskCacheStrategy(DiskCacheStrategy.ALL).circleCrop();
        Glide.with(context).load(orgnat.getHeadPath()).apply(requestOptions1).into(holder.headImg);
        holder.name.setText(orgnat.getName());
        holder.lev.setText(orgnat.getLevel());
        //图片
        List<Img> imgList = dataSource.get(position).getImgPathList();
        GridViewItemImgAdapter gridViewItemImgAdapter = new GridViewItemImgAdapter(context, imgList, R.layout.grid_view_item);
        holder.gridView.setAdapter(gridViewItemImgAdapter);
        //文本
        holder.title.setText("/*" + activities.getTitle() + "*/");
        String content1 = "";
        if (activities.getContent().length() > 100) {
            content1 = activities.getContent().substring(0, 100) + "...";
        } else {
            content1 = activities.getContent();
        }
        holder.content.setText(content1);
        //标签
        String[] strings = activities.getLabel().split(",");
        String s = "";
        for (int i = 0; i < strings.length; i++) {
            s = s + strings[i] + "\u3000";
        }
        holder.list_biaoqian.setText(s);
        //点击量
        holder.num_views.setText("点击量 " + activities.getViewNum());
        //点击头像进入组织介绍页面
        final Gson gson = new GsonBuilder().serializeNulls().create();
        holder.headImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String o = gson.toJson(orgnat);
                Intent intent = new Intent(context, OrganizationMainActivity.class).putExtra("organt", o);
                context.startActivity(intent);
            }
        });
        holder.content_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String a = gson.toJson(activities);
                Intent intent1 = new Intent(context, ActivityDetail.class).putExtra("activity", a);
                context.startActivity(intent1);
            }
        });


        //申请参加活动
        if(role==1){

            if (activities.getIsSetJoinNum() == 1 && activities.getStatus() == 1) {
                holder.button.setVisibility(View.VISIBLE);
                int is_apply = activities.getUserApplyStatus();


                holder.button.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if(isIdentity==1){
                            if (is_apply == 0|| is_apply==4) {//未申请，可以申请,申请失败可以再次申请
                                //点击之后就从数据库获取数据，活动申请状况
                                whetherToApply(activities.getId(),position);
                            } else if (is_apply == 1) {//已经提交申请，简单提示即可
                                Toast toast4 = Toast.makeText(context, "已提交申请，申请结果请在消息中查看通知", Toast.LENGTH_SHORT);
                                toast4.setGravity(Gravity.CENTER, 0, 0);
                                TextView v = (TextView) toast4.getView().findViewById(android.R.id.message);
                                v.setTextColor(Color.parseColor("#0d4ff4"));
                                toast4.show();
                            } else if (is_apply == 2) {//申请成功
                                Toast toast4 = Toast.makeText(context, "已申请成功，记着按时参加活动哟", Toast.LENGTH_SHORT);
                                toast4.setGravity(Gravity.CENTER, 0, 0);
                                TextView v = (TextView) toast4.getView().findViewById(android.R.id.message);
                                v.setTextColor(Color.parseColor("#0d4ff4"));
                                toast4.show();
                            }else if(is_apply==3){//该活动已经占位，尚未提交,直接进入
                                Intent intent = new Intent(context, ApplyActivities.class).putExtra("aId",activities.getId()).putExtra("position",randomPosition);
                                context.startActivity(intent);
                            }



                        }else {
                            Toast toast4 = Toast.makeText(context, "您尚未实名验证，请先实名验证才可申请", Toast.LENGTH_SHORT);
                            toast4.setGravity(Gravity.CENTER, 0, 0);
                            TextView v = (TextView) toast4.getView().findViewById(android.R.id.message);
                            v.setTextColor(Color.parseColor("#0d4ff4"));
                            toast4.show();
                        }


                    }
                });

                notifyDataSetChanged();
            }else if(activities.getIsSetJoinNum() == 1 && activities.getStatus() == 0){//活动结束
                holder.button.setVisibility(View.VISIBLE);
                holder.button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast toast4 = Toast.makeText(context, "活动已结束，请关注下期活动", Toast.LENGTH_SHORT);
                        toast4.setGravity(Gravity.CENTER, 0, 0);
                        TextView v = (TextView) toast4.getView().findViewById(android.R.id.message);
                        v.setTextColor(Color.parseColor("#0d4ff4"));
                        toast4.show();
                    }
                });
            }else {
                holder.button.setVisibility(View.VISIBLE);
                holder.button.setVisibility(View.INVISIBLE);
            }

        }else{
            holder.button.setVisibility(View.VISIBLE);
            holder.button.setVisibility(View.INVISIBLE);
        }

        notifyDataSetChanged();
        return view;
    }

    public void whetherToApply(int id,int position) {
        randomPosition=position;
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody body = new FormBody.Builder().add("aId", String.valueOf(id)).build();
        final Request request = new
                Request.Builder().url(Constant.url + "activities/whetherToApply").post(body).build();
        final Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 71;
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Gson gson = new Gson();
                ActivityApplyData activityApplyData = gson.fromJson(str, ActivityApplyData.class);
                int free = activityApplyData.getFreeNum();
                if(free>0){//占住一个申请位置
                    Log.e("sss","占位");
                    zhanWei(activityApplyData,position);
                }else {
                    Log.e("sss","活动已满");
                        Message message=new Message();
                        message.what=74;
                        message.obj=str;
                        handler.sendMessage(message);
                }
            }
        });
    }
    private void toNext(ActivityApplyData activityApplyData, int position) {
         if (dataSource.get(position).getToApply()==1) {//占位成功
            Message message=new Message();
            message.what=73;
            Gson gson=new Gson();
            message.obj=gson.toJson(activityApplyData);
            handler.sendMessage(message);


        }
    }

    public void quXiaoZhanWei(int aId,int position) {

        Log.e("取消占位","取消占位");
        if(dataSource.get(position).getToApply()==1){
            OkHttpClient okHttpClient = new OkHttpClient();
            FormBody body = new FormBody.Builder().add("aId", String.valueOf(aId)).build();
            final Request request = new
                    Request.Builder().url(Constant.url + "activities/CancelApply").post(body).build();
            final Call call = okHttpClient.newCall(request);
            call.enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    dataSource.get(position).setToApply(1);
                    Message message = new Message();
                    message.what = 71;
                    handler.sendMessage(message);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    Log.e("s123", str + "");
                    int re= Integer.parseInt(str);
                    if(re==1){
                        //成功，结束占位
                        is=0;
                        dataSource.get(position).setToApply(0);
                    }
                }
            });

        }
    }
    public void zhanWei( ActivityApplyData activityApplyData,int position) {
        int aId=activityApplyData.getaId();
        if(dataSource.get(position).getToApply()!=1) {
            OkHttpClient okHttpClient = new OkHttpClient();
            FormBody body = new FormBody.Builder().add("aId", String.valueOf(aId)).build();
            final Request request = new
                    Request.Builder().url(Constant.url + "activities/startApply").post(body).build();
            final Call call = okHttpClient.newCall(request);
            call.enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("sss","占位失败：网络失败");
                    dataSource.get(position).setToApply(0);
                    Message message = new Message();
                    message.what = 71;
                    handler.sendMessage(message);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    Log.e("s123", str + "");
                    int re = Integer.parseInt(str);
                    if (re == 1) {
                        //成功，开始
                        Log.e("sss","占位成功");
                        dataSource.get(position).setToApply(1);
                        toNext(activityApplyData,position);//下一步
                    }else {
                        Log.e("sss","占位失败：网络失败2");
                        Message message = new Message();
                        message.what = 71;
                        handler.sendMessage(message);
                    }
                }
            });
        }else {
            Message message=new Message();
            message.what=72;
            message.obj=1;
            handler.sendMessage(message);
        }
    }
    public class ViewHolder {
        public TextView title;
        public ImageView headImg;
        public TextView name;
        public TextView lev;
        public TextView upDay;
        public TextView upTime;
        public TextView content;
        public NoScrollGridView gridView;
        public TextView list_biaoqian;
        public TextView num_views;
        public LinearLayout content_main;
        public Button button;
        public TextView ac_status;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {

            if (msg.what == 71) {
                Toast toast3 = Toast.makeText(context, "网络连接错误", Toast.LENGTH_SHORT);
                toast3.setGravity(Gravity.CENTER, 0, 0);
                TextView v = (TextView) toast3.getView().findViewById(android.R.id.message);
                v.setTextColor(Color.parseColor("#0d4ff4"));
                toast3.show();
            }
            if (msg.what == 72) {
                int i = Integer.parseInt(msg.obj.toString());
                if (i == 1) {
                    Toast toast5 = Toast.makeText(context, "已提交申请，申请结果请在消息中查看通知", Toast.LENGTH_SHORT);
                    toast5.setGravity(Gravity.CENTER, 0, 0);
                    TextView v = (TextView) toast5.getView().findViewById(android.R.id.message);
                    v.setTextColor(Color.parseColor("#0d4ff4"));
                    toast5.show();
                } else {
                    Toast toast4 = Toast.makeText(context, "网络错误，请重新申请", Toast.LENGTH_SHORT);
                    toast4.setGravity(Gravity.CENTER, 0, 0);
                    TextView v = (TextView) toast4.getView().findViewById(android.R.id.message);
                    v.setTextColor(Color.parseColor("#0d4ff4"));
                    toast4.show();
                }
            }
            if(msg.what==73){

                Gson gson=new Gson();
                ActivityApplyData activityApplyData=gson.fromJson(msg.obj.toString(),ActivityApplyData.class);
                int applying = activityApplyData.getApplyingNum();
                int join = activityApplyData.getJoinNum();
                int free = activityApplyData.getFreeNum();
                 dialog = new AlertDialog.Builder(context).create();
                dialog.setCanceledOnTouchOutside(false);//点击空白区的时候(不调用dismiss())
                dialog.show();  //注意：必须在window.setContentView之前show
                Window window = dialog.getWindow();
                window.setContentView(R.layout.is_apply);
                TextView a_ing = window.findViewById(R.id.applying);
                TextView succeed = window.findViewById(R.id.success_apply);
                TextView a_free = window.findViewById(R.id.apply_free);
                TextView dao_ji_shi=window.findViewById(R.id.dao_ji_shi);
                /**
                 * CountDownTimer timer = new CountDownTimer(3000, 1000)中，
                 * 第一个参数表示总时间，第二个参数表示间隔时间。
                 * 意思就是每隔一秒会回调一次方法onTick，然后1秒之后会回调onFinish方法。
                 */
                 timer = new CountDownTimer(30000, 1000) {
                    public void onTick(long millisUntilFinished) {
                        dao_ji_shi.setText(millisUntilFinished / 1000 + "秒");
                    }

                    public void onFinish() {
                        //如果占位成功，取消占位
                        Log.e("被调用","被调用");
                        if(is==1){
                            quXiaoZhanWei(activityApplyData.getaId(),randomPosition);
                        }
                        dialog.dismiss();
                    }
                };
                //调用 CountDownTimer 对象的 start() 方法开始倒计时，也不涉及到线程处理
                timer.start();
                a_ing.setText("正在提交:" + applying + "人");
                succeed.setText("提交申请:" + join + "人");
                a_free.setText("空余:" + free + "人");
                Button yesButton = window.findViewById(R.id.apply_ok);
                Button no = window.findViewById(R.id.apply_no);
                //点击确定按钮让对话框消失
                yesButton.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        //进入申请页面判断当前是否可以申请
                        is=0;
                        //点击确定后开启申请，申请位置设为3：表示正在提交申请，尚未提交
                        Message message=new Message();
                        message.what=76;
                        message.obj=activityApplyData.getaId();
                        handler.sendMessage(message);

                    }
                });
                no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //取消占位
                        timer.cancel();
                        quXiaoZhanWei(activityApplyData.getaId(),randomPosition);
                        dialog.dismiss();
                    }
                });

            }
            if(msg.what==74){
                Gson gson=new Gson();
                Log.e("s",msg.obj.toString());
                ActivityApplyData activityApplyData=gson.fromJson(msg.obj.toString(),ActivityApplyData.class);
                int applying = activityApplyData.getApplyingNum();
                int join = activityApplyData.getJoinNum();
                int free = activityApplyData.getFreeNum();
                final AlertDialog dialog = new AlertDialog.Builder(context).create();
                dialog.show();  //注意：必须在window.setContentView之前show
                Window window = dialog.getWindow();
                window.setContentView(R.layout.is_apply);
                TextView a_ing = window.findViewById(R.id.applying);
                TextView succeed = window.findViewById(R.id.success_apply);
                TextView a_free = window.findViewById(R.id.apply_free);
                a_ing.setText("正在提交:" + applying + "人");
                succeed.setText("提交申请:" + join + "人");
                a_free.setText("空余:" + free + "人");
                Button yesButton = window.findViewById(R.id.apply_ok);
                Button no = window.findViewById(R.id.apply_no);
                //点击确定按钮让对话框消失
                yesButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //信息提示：申请已满，关注下次活动或稍后再试
                        Toast toast4 = Toast.makeText(context, "申请已满，关注下次活动或稍后再试", Toast.LENGTH_SHORT);
                        toast4.setGravity(Gravity.CENTER, 0, 0);
                        TextView v2 = (TextView) toast4.getView().findViewById(android.R.id.message);
                        v2.setTextColor(Color.parseColor("#0d4ff4"));
                        toast4.show();
                        dialog.dismiss();
                    }
                });
                no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });

            }
            if(msg.what==76){
                int aId= Integer.parseInt(msg.obj.toString());
                Log.e("申请参加第一步","ss");
                OkHttpClient okHttpClient = new OkHttpClient();
                FormBody body = new FormBody.Builder().add("aId", String.valueOf(aId))
                        .add("userId", String.valueOf(userId))
                        .build();
                Log.e("申请参加第2步","ss");
                final Request request2 = new
                        Request.Builder().url(Constant.url + "activities/toApplyToJoin").post(body).build();
                final Call call0 = okHttpClient.newCall(request2);
                call0.enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Message message=new Message();
                        message.what=71;
                        Log.e("shenqshibai","ss");
                        handler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String str = response.body().string();
                        if(str.equals("1")){
                            Log.e("shenqshibai22222222","ss");
                            startApplyActivity(aId);
                        }else {
                            Log.e("ssss123455676","fanhuideshi"+str);
                        }
                    }
                });
            }
        }
    };

    public void startApplyActivity(int aId) {
        Log.e("已准备完毕，开始进入表单页面","ss");
        timer.cancel();
        dialog.dismiss();
        Intent intent = new Intent(context, ApplyActivities.class).putExtra("aId",aId).putExtra("position",randomPosition);
        context.startActivity(intent);
    }
    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveMsg(EventMessage message) {
        Log.e("me",message.toString());
        dataSource.get(message.getPosition()).setUserApplyStatus(message.getApplyStatus());
        dataSource.get(message.getPosition()).setToApply(0);
        Log.e("appstatus",dataSource.get(message.getPosition()).getUserApplyStatus()+"");
        notifyDataSetChanged();
    }

}
